package com.stone.serverless.event.service;

import com.stone.serverless.event.EventComponentProvider;
import com.stone.serverless.event.domain.EventKey;
import com.stone.serverless.event.domain.EventListenerObject;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/2/7 10:25
 * @Version: 1.0.0
 */
@Service
public class EventBus implements EventBusService, InitializingBean {

    private static Map<String, EventListenerObject> hashMap = new ConcurrentHashMap<>();


    public static void unListener(ClassLoader classLoader) {
        for (Map.Entry<String, EventListenerObject> entry : hashMap.entrySet()) {
            String key = entry.getKey();
            EventListenerObject value = entry.getValue();
            if (value.getMethod().getClass().getClassLoader().hashCode() == classLoader.hashCode()) {
                hashMap.remove(key);
            }
        }

    }

    @Override
    public void publish(EventKey event) {

        EventListenerObject eventListenerObject = hashMap.get(event.getKey());
        switch (event.getEventTypeEnum()) {
            case REMOTE:
                System.out.println("暂未实现啊");
                break;
            default:
                Object method = eventListenerObject.getMethod();
                if (method instanceof Supplier) {
                    ((Supplier<?>) method).get();

                }
                break;
        }

    }

    @Override
    public <T> void listener(String test, Supplier<T> test1, Object obj) {
        EventListenerObject eventListenerObject = new EventListenerObject(test, test1, obj);
        hashMap.put(test, eventListenerObject);
    }

    @Override
    public <T> void listener(String key, Supplier<T> test1) {
        EventListenerObject eventListenerObject = new EventListenerObject(key, test1);
        hashMap.put(key, eventListenerObject);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        EventComponentProvider.INSTANCE.add(this);
    }
}
